<template>
	<view class="index-container">
		<!-- 顶部导航 -->
		<view class="nav-bar" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="title">对话</view>
			<text class="title-extra">创建AI</text>
			<view class="add-btn" @tap="gotoCreate">
				<text class="iconfont icon-add" />
			</view>
		</view>

		<!-- AI标签栏 -->
		<AITabs v-model="currentTab" :list="tabList" @change="loadDevices" />

		<!-- AI列表 -->
		<scroll-view class="device-list" scroll-y>
			<AICard v-for="device in deviceList" :key="device.id" :id="device.id" :avatar="device.avatar"
				:name="device.name" :description="device.description" :chatCount="device.chatCount"
				:isCollected="device.isCollected" @click="gotoChat(device)" @collect="toggleCollect" />
		</scroll-view>

		<!-- 聊天框 -->
		<ChatBox :messages="chatMessages" @send="sendMessage" />
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted
	} from 'vue' // 添加 onMounted
	import {
		useUserStore,
		useDeviceStore,
		useChatStore
	} from '@/stores'
	import {
		system
	} from '@/utils'

	// 状态管理
	const userStore = useUserStore()
	const deviceStore = useDeviceStore()
	const chatStore = useChatStore()

	// 状态栏高度
	const statusBarHeight = system.getNavBarHeight()

	// 标签页数据
	const tabList = [{
			label: '推荐',
			value: 'recommend'
		},
		{
			label: '最新',
			value: 'latest'
		},
		{
			label: '热门',
			value: 'popular'
		},
		{
			label: '收藏',
			value: 'collected'
		}
	]
	const currentTab = ref('recommend')

	// AI列表数据
	const deviceList = computed(() => {

		const devices = deviceStore.privateDevices || [] s
		console.log('首页设备列表详细数据:',
			devices.map(d => ({
				id: d.id,
				name: d.name,
				icon: d.icon,
				description: d.description
			}))
		)
		return devices

		switch (currentTab.value) {
			case 'recommend':
				return deviceStore.recommendDevices
			case 'latest':
				return deviceStore.latestDevices
			case 'popular':
				return deviceStore.popularDevices
			case 'collected':
				return deviceStore.collectedDevices
		}
	})

	// 聊天信息
	const chatMessages = computed(() => chatStore.messages)

	// 加载设备列表
	const loadDevices = async (tab) => {
		await deviceStore.loadDevices(tab)
	}

	// 切换收藏状态
	const toggleCollect = async (deviceId) => {
		await deviceStore.toggleCollect(deviceId)
	}

	// 进入聊天页面
	const gotoChat = (device) => {
		chatStore.setCurrentDevice(device.id)
		uni.navigateTo({
			url: `/pages/chat/chat?id=${device.id}`
		})
	}

	// 进入创建页面
	const gotoCreate = () => {
		uni.navigateTo({
			url: '/pages/create/create'
		})
	}

	// 发送消息
	const sendMessage = async (message) => {
		await chatStore.sendMessage(message)
	}

	// 页面加载时初始化数据
	onMounted(() => {
		loadDevices(currentTab.value)
	})
</script>